<template>
  <div>
    <el-card style="width: 700px;">
      <el-form
        v-if="formJSON.formData"
        :model="formJSON.formData"
        :rules="formJSON.rules"
        v-bind="formJSON.formConfig"
        ref="formRef">
        <dynamic-form
          v-if="formJSON.components"
          :components="formJSON.components"
          :formData="formJSON.formData"
        />
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';
import DynamicForm from './DynamicForm.vue';
import { calculateFunction, initFormData } from './DynamicForm.js';
import { ElMessage } from 'element-plus';

const formJSON = ref({ formData: {}, rules: {}, components: [] });
const formRef = ref(null);

async function getJson() {
  try {
    const response = await fetch('/json/demo.json');
    formJSON.value = await response.json();
    formJSON.value['formData'] = initFormData(formJSON.value);
  } catch (error) {
    console.error('Failed to load JSON:', error);
  }
}

onMounted(() => {
  getJson();
});

// 监听计算字段的变化
watch(
  () => formJSON.value.formData,
  () => {
    calculateFunction(formJSON.value.components, formJSON.value.formData);
  },
  { deep: true }
);

function submitForm() {
  if (!formRef.value) {
    ElMessage.error('表单未正确初始化');
    return;
  }

  formRef.value.validate((valid, invalidFields) => {
    if (valid) {
      ElMessage.success('表单验证成功！');
    } else {
      ElMessage.error('表单验证失败！');
      for (const field in invalidFields) {
        ElMessage.error(invalidFields[field][0].message);
      }
    }
  });
}
</script>

<style scoped></style>